<?php
class Aaron_Easytopsell_Block_Topseller extends Mage_Catalog_Block_Product_Abstract {
//	protected function _construct() {
//		parent::_construct();
//		$this->addData(array(
//			'cache_lifetime' => 86400,
//			'cache_tags' => array('magazentoeasytopsell_home'),
//		));
//
//	}
	protected $_catId = null;
	protected $_daysLimit = 365;
	protected $_itemLimit = 5;

	public function setCategoryId($catId){
        if (intval($catId) > 0) {
			$this->_catId = $catId;
		}
		return $this;
	}

	public function setDaysLimit($daysLimit){
        if (intval($daysLimit) > 0) {
			$this->_daysLimit = $daysLimit;
		}
		return $this;
	}

	public function setItemLimit($limit){		
        if (intval($limit) > 0) {
            $this->_itemLimit = intval($limit);
        }
        return $this;
    }

	protected function _beforeToHtml() {

		$storeId = Mage::app()->getStore()->getId();
		$sellDate=$this->getSellDate($this->_daysLimit);
		$collection = Mage::getResourceModel('reports/product_sold_collection')
					->addOrderedQty()
					->setStoreId($storeId)
					->addStoreFilter($storeId)
					->setDateRange($sellDate['startdate'], $sellDate['todaydate']) //
					->addUrlRewrite()
					->addAttributeToFilter('visibility', array('in' => array(Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG, Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)))
					->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
					->setOrder('ordered_qty', 'desc')
					->setPageSize($this->_itemLimit)
					->setCurPage(1)
					->setOrder('ordered_qty', 'desc');

		if ($this->_catId) {
			$category = $this->getCategory($this->_catId);
			$collection->addCategoryFilter($category); 
		}


		$this->setProductCollection($collection);
		return parent::_beforeToHtml();
	}
	
	public function getSellDate($days) {
        $date=array();
        $date['todaydate'] = date('Y-m-d H:i:s', time());
        $date['startdate'] = date('Y-m-d H:i:s', time() - 60 * 60 * 24 * $days);
        return $date;
    }

    public function getCategory ($id){
		$categoryId = $id;
		if (!$categoryId || !is_numeric($categoryId))
			$category = Mage::registry("current_category");
		else {
			$category = Mage::getModel("catalog/category")->load($categoryId);
			if (!$category->getId())
				$category = Mage::registry("current_category");
		}
		return $category;
    }
}